在以下 Express 函数中:
app.get('/user/:id', function(req, res){ res.send('user' + req.params.id); });
req和是什么res?它们代表什么,它们的含义是什么,它们是做什么的?
req
res
谢谢!
req是一个对象,包含有关引发事件的 HTTP 请求的信息。作为对 的响应req,您使用res发送回所需的 HTTP 响应。
这些参数可以任意命名。如果更清楚,您可以将该代码更改为此:
app.get('/user/:id', function(request, response){ response.send('user ' + request.params.id); });
编辑:
假设你有这个方法:
app.get('/people.json', function(request, response) { });
该请求将是一个具有以下属性的对象(仅举几例):
request.url
"/people.json"
request.method
"GET"
app.get()
request.headers
request.headers.accept
request.query
/people.json?foo=bar
request.query.foo
"bar"
要响应该请求,您可以使用响应对象来构建您的响应。扩展people.json示例:
people.json
app.get('/people.json', function(request, response) { // We want to set the content-type header so that the browser understands // the content of the response. response.contentType('application/json'); // Normally, the data is fetched from a database, but we can cheat: var people = [ { name: 'Dave', location: 'Atlanta' }, { name: 'Santa Claus', location: 'North Pole' }, { name: 'Man in the Moon', location: 'The Moon' } ]; // Since the request is for a JSON representation of the people, we // should JSON serialize them. The built-in JSON.stringify() function // does that. var peopleJSON = JSON.stringify(people); // Now, we can use the response object's send method to push that string // of people JSON back to the browser in response to this request: response.send(peopleJSON); });